using Newtonsoft.Json;
using SCADAEditor.Component;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace SCADAEditor
{
    /// <summary>
    /// 项目管理类，负责SCADA项目的加载和保存
    /// 功能：
    /// - 管理项目数据的序列化和反序列化
    /// - 处理组件属性的类型转换
    /// - 维护窗口和组件的数据结构
    /// </summary>
    public class ProjectManager
    {
        private readonly Dictionary<Type, Func<object, object>> _propertyConverters = new Dictionary<Type, Func<object, object>>();
        private readonly ComponentList _componentList;
        private readonly WinformTreeDatastruct _treeData;

        public ProjectManager(ComponentList componentList, WinformTreeDatastruct treeData)
        {
            _componentList = componentList;
            _treeData = treeData;
            InitializePropertyConverters();
        }

        private void InitializePropertyConverters()
        {
            _propertyConverters[typeof(Color)] = value => Color.FromArgb(Convert.ToInt32(value));
            _propertyConverters[typeof(Font)] = value => new FontConverter().ConvertFromString(value.ToString());
            _propertyConverters[typeof(FlashInterval)] = value => (FlashInterval)Convert.ToInt32(value);
            _propertyConverters[typeof(DateFormat)] = value => (DateFormat)Convert.ToInt32(value);
            _propertyConverters[typeof(TimeFormat)] = value => (TimeFormat)Convert.ToInt32(value);
            _propertyConverters[typeof(DeviceType)] = value => (DeviceType)Convert.ToInt32(value);
        }

        public void SaveProject(string filePath,List<string> treeNodes)
        {
            var projectData = new ProjectData();
    
            // 获取所有窗口数据
            foreach (var nodeText in treeNodes) // 直接使用TreeWinformList的Nodes属性
            {
               var colonIndex = nodeText.IndexOf('：');
                if (colonIndex > 0 && int.TryParse(nodeText.Substring(0, colonIndex), out int windowId))
                {
                
                    var windowData = new WindowData
                    {
                        Id = windowId,
                        Name = nodeText.Substring(colonIndex + 1)
                    };
                    
                    // 获取窗口组件
                    var components = _treeData.GetWindowComponents(windowId);
                    foreach (var component in components)
                    {
                        windowData.Components.Add(new ComponentData
                        {
                            Type = _componentList.GetComponentType(component),
                            Position = component.Position,
                            Properties = component.ToJson()
                        });
                    }
                    
                    projectData.Windows.Add(windowData);
                }
            }
            
            // 序列化为JSON并保存
            var json = JsonConvert.SerializeObject(projectData, Formatting.Indented);
            File.WriteAllText(filePath, json);
        }

        public void LoadProject(string filePath)
        {
            try
            {
                // 读取JSON文件
                var json = File.ReadAllText(filePath);
                var projectData = JsonConvert.DeserializeObject<ProjectData>(json);
                
                // // 清空当前树视图和组件数据
                // _treeData.Clear();
                
                // 重建窗口和组件
                foreach (var windowData in projectData.Windows)
                {
                    // 创建窗口节点
                    var windowNode = _treeData.AddWindow(windowData.Name, new Size(800, 600));
                    
                    // 重建组件
                    foreach (var componentData in windowData.Components)
                    {
                        var component = _componentList.CreateComponent(componentData.Type);
                        if (component != null)
                        {
                            component.Position = componentData.Position;
                            
                            // 设置组件属性
                            if (componentData.Properties != null)
                            {
                                foreach (var prop in componentData.Properties)
                                {
                                    var property = component.GetType().GetProperty(prop.Key);
                                    if (property != null && property.CanWrite)
                                    {
                                        if (_propertyConverters.TryGetValue(property.PropertyType, out var converter))
                                        {
                                            property.SetValue(component, converter(prop.Value));
                                        }
                                        else
                                        {
                                            property.SetValue(component, prop.Value);
                                        }
                                    }
                                }
                            }
                            
                            // 添加到窗口
                            _treeData.AddComponentToWindow(windowData.Id, component);
                        }
                    }
                }


                // 在加载完成后重新注册信号
                foreach (var windowData in projectData.Windows)
                {
                    foreach (var component in _treeData.GetWindowComponents(windowData.Id))
                    {
                        if (component is StatusIndicatorComponent indicator && 
                            !string.IsNullOrEmpty(indicator.OnOffSignalName))
                        {
                            SignalService.Instance.RegisterSignalHandler(
                                indicator.OnOffSignalName, 
                                value => indicator.OnOff = value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"载入项目失败: {ex.Message}", ex);
            }
        }
    }
}